package com.car.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.car.dal.object.TgUser;
import com.car.util.Constants;
import com.car.util.UserUtil;


public class CheckLoginFilter implements Filter {

	private ApplicationContext context;
	private static final Logger logger = Logger
			.getLogger(CheckLoginFilter.class);

	public void init(FilterConfig config) throws ServletException {
		context = WebApplicationContextUtils.getWebApplicationContext(config
				.getServletContext());
	}

	@SuppressWarnings("unused")
	public void doFilter(ServletRequest srequest, ServletResponse sresponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;

		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.substring(contextPath.length());
		// 绑定热门车辆

		boolean forbidden = false;
		// Cache<String, Serializable> cache =
		// CacheUtil.getCache(CacheNameSpace.User);
		// cache.delete("USER-5");
		// cache.delete("USER-admin");
		/** 请求增加用户对象 **/
		TgUser user = UserUtil.getCookieUser();
		if (user != null) {
			request.setAttribute(Constants.USER_QER, user);
		}
		if (uri.contains("/sys/login.htm")||uri.contains("/sys/adminlogin.htm") ||uri.contains("oa") ||uri.contains("admin")|| uri.contains("/ask_answer_read")) {
			chain.doFilter(srequest, sresponse);
		}else {
			if (user == null) {
				response.sendRedirect(contextPath + "/sys/login.htm");
				return;
			}
			chain.doFilter(srequest, sresponse);
		}
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
		
}
